﻿

using IotClientService.Models.Lg;
using IotClientService.Models.Option;
using IotClientService.Services;
using IotContract.Enums;
using IotContract.Models.Mqtt;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XT.Common.Config;
using XT.Common.Extensions;

namespace IotClientService.Handles.lgs;
/// <summary>
/// 注液机
/// </summary>
public class LgHandleLiquid:LgHandleBase
{
    public LgHandleLiquid(ILgApiService lgCallApiService) : base(lgCallApiService)
    {
        
    }

    public override IotEquipType EquipType { get; set; } = IotEquipType.LIQUID;
    /// <summary>
    /// 处理消息
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public override async Task<bool> HandleMsg(LgMsgInfo msg)
    {
        string replyCmd = string.Empty;
        switch (msg.Command)
        {
            // 作业实处理Data报告
            case "901":
                replyCmd = "902";
                await Handle901(msg, replyCmd);
                break;
           
            // 设备状态报告指示回应
            case "910":
               await Handle910(msg, "910");
                // send 833 

                break;
            // 设备状态报告
            case "913":
               await Handle913(msg, "913");

                break;
            // 作业mode报告
            case "917":
                replyCmd = "918";
               await Handle917(msg, replyCmd);
                break;
            // 通信状态报告邀请
            case "925":
                replyCmd = "926";
               await Handle925(msg, replyCmd);
                break;
            // 通信状态报告回应
            case "926":
               await Handle926(msg, "926");
                break;
            // 电芯投入报告
            case "933":
                replyCmd = "934";
              await  Handle933(msg, replyCmd);
                break;
          
            // 未知命令,错误
            case "981":
                await Handle981(msg, "981");
                break;
            // 设备Trouble报告
            case "985":
                await Handle985(msg, "985");
                break;
            
          
            // 设置时间指示
            case "999":
               await Handle999(msg, replyCmd);
                break;
            default:
                // send 981
               await Handle981(msg, "981");
                break;
        }
        return true;
    }
    /// <summary>
    /// 作业实处理Data报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle901(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
       
        // 1 cellid  24
        string cellId = msg.Message.Substring(18, 24);
        // ng判定  0:ok 1:ng
        string ngCharge = msg.Message.Substring(42, 1);
        // ng code
        string ngCode = msg.Message.Substring(43, 4);
        // 结果数据
        string result = msg.Message.Substring(47, 105);

        LgLiquidResult lgLiquidResult = new LgLiquidResult
        {
            StartTime = DateTime.ParseExact(result.Substring(0, 14),"yyyyMMddHHmmss", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss"),
            BellJarVacuumValue = result.Substring(14, 4).To<int>(),
            BellJarVacuumTime = result.Substring(18, 3).To<int>(),
            BellJarHighPressureValue = result.Substring(21, 4).To<int>(),
            BellJarHighPressureTime = result.Substring(25, 3).To<int>(),
            BellJarCycleCount = result.Substring(28, 2).To<int>(),
            CellWeightBeforeInjection = result.Substring(30, 7).To<double>(),
            CellWeightAfterInjection = result.Substring(37, 7).To<double>(),
            TotalInjectionVolume = result.Substring(44, 6).To<double>(),
            CellLeakTestResult = result.Substring(50, 1).To<int>(),
            InjectionPumpNumber = result.Substring(51, 1).To<int>(),
            SealantPlug = result.Substring(52, 1).To<int>(),
            HeliumFillingValue = result.Substring(53, 4).To<double>(),
            VacuumValueBeforeHelium = result.Substring(57, 4).To<double>(),
            SealantPlugDetectionHeight = result.Substring(61, 5).To<double>(),
            SealantPlugDetectionResult = result.Substring(66, 1).To<int>(),

            CellThicknessTestResult = result.Substring(67, 1).To<int>(),
            CellThicknessValue = result.Substring(68, 5).To<double>(),
            EndTime = DateTime.ParseExact(result.Substring(73, 14), "yyyyMMddHHmmss", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss"),
            InjectionResult =result.Substring(87,1).To<int>(),
            SecondInjectionVolume=result.Substring(88,8).To<double>(),
            LeakageVolume=result.Substring(96,8).To<double>(),
            LeakageVolumeJudgement=result.Substring(104,1).To<int>()
            

        };

        var rep=  await Api.CommitLiquidResult(new Models.Lg.Remote.LgLiquidResultRequest
        {
            EquipNum=Equip.Num,
            EquipType = this.EquipType,
            ProgramType = Equip.ProgramType,
            Cell = cellId,
            Ng = ngCharge.To<int>(),
            NgCode = ngCode,
            Data = lgLiquidResult
        });
        if (!rep.Success)
        {
            Equip.ExMessage = rep.Message;
            return;
        }
        // 24长度
        var cellid = cellId.PadRight(24,' ');
        // 0:ok 1:ng
        var ret = rep.Result.Ret;
        var ng = rep.Result.NgCodes?.FirstOrDefault() ?? "0000";

        sendMsg.Body = $"{cellid}{ret}{ng}";
        sendMsg.IsSend = true;
        InvokeSend(sendMsg);


    }

  
   
   
   
   
   
    /// <summary>
    /// 电芯投入报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle933(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
        // 托盘
        var cellid = msg.Message.Substring(18,24);

        Equip.Remark = $"cell load:{cellid}";


        
        Equip.Obj = cellid;

       var result= await Api.CommitLiquidEnter(new Models.Lg.Remote.LgCellEnterRequest
        {
            Cell = cellid,
            EquipNum = Equip.Num,
            EquipType = this.EquipType,
            ProgramType = Equip.ProgramType
        });
        if(!result.Success)
        {
            Equip.ExMessage = result.Message;
            return;
        }
        #region 传输body
        
        var cell = cellid;
        // 0:ok 1:ng 
        int ng = 0;
        var ngCode = result.Result.NgCode.PadLeft(4, '0');

        // 一次注液数据
        var liquidData = result.Result.FirstData.ToString();
        // 电池判定条件
        var liquidJudge = result.Result.CellJudage.ToString();

        #endregion
        sendMsg.Body = $"{cell}{ng}{ngCode}{liquidData}{liquidJudge}";
        sendMsg.IsSend = true;
        InvokeSend(sendMsg);
    }

    
  
}
